*. Create additional variables

* Indicator of devaluation and recent devaluation
gen app = 0
gen appr= 0
replace app=1 if largeDevaluation==1
replace appr=1 if largeDevaluation==1 & year>=1995 & ccode!="MEX"
foreach t of num 1/7{
gen app_l`t'=l`t'.app
gen banking_l`t' = l`t'.banking
gen sovereign_l`t' = l`t'.sovereign
gen restructuring_l`t' = l`t'.restructuring
}
egen deva = rowtotal(app app_l1 app_l2 app_l3 app_l4 )
egen financial = rowtotal(banking banking_l1 banking_l2 banking_l3 banking_l4)  
egen default = rowtotal(sovereign sovereign_l1 sovereign_l2 sovereign_l3 sovereign_l4) 
egen restru = rowtotal(restructuring restructuring_l1 restructuring_l2 restructuring_l3 restructuring_l4) 

* Prepare decadal-specific dummies
gen decade70=0
gen decade80=0
gen decade90=0
gen decade00=0
replace decade70=1 if year<1980
replace decade80=1 if year>=1980 & year<1990
replace decade90=1 if year>=1990 & year<2000
replace decade00 = 1 if year>=2000

* decadal-specific linear time trends (for specification 4 of Table A4)
gen year80 = year*decade80
gen year90 = year*decade90
gen year00 = year*decade00

* indicator of "treated" countries (any devaluation, any recent devaluation)
bys ccode: egen anycurrency = total(app)
bys ccode: egen anycurrency_recent = total(appr)
gen D=0
replace D=1 if anycurrency>=1
gen Recent=0
replace Recent=1 if anycurrency_recent>=1

* decadal and group-specific linear time trends
gen year80D = year*decade80 * D
gen year90D = year*decade90 * D
gen year00D = year*decade00 * D
gen year80J = year*decade80 * Recent
gen year90J = year*decade90 * Recent
gen year00J = year*decade00 * Recent

* group-specific linear time trends
gen yearD = year * D
gen yearJ = year * Recent

* indicator of financial crisis in 2008 but not large devaluation
gen BankNoDeva2008 = 0
replace BankNoDeva2008=1 if banking==1 & year==2008 & app==0

* tariffs
gen logtau = log(1+tariff1)

* Variables for event study:
preserve
keep id ccode year country largeDevaluation lRER rer
gen currency=0
replace currency=1 if largeDevaluation==1
sort id year
gen rer_l1 = l1.rer
foreach t of num 2/5{
gen preapp`t' = (l1.rer-l`t'.rer)/l`t'.rer*100 // positive means pre-deva appreciation
}
gen preapp = preapp5
replace preapp=preapp4 if preapp5==. & preapp4!=.
replace preapp=preapp3 if preapp5==. & preapp4==. & preapp3!=.
replace preapp=preapp2 if preapp5==. & preapp4==. & preapp3==. & preapp2!=.
keep if largeDevaluation!=.
keep ccode year preapp
cd temp
save preapp.dta, replace
cd ..
restore
sort ccode year
merge 1:1 ccode year using "temp/preapp.dta"
drop _merge
